package org.example.clouddemo.user.service.common.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.clouddemo.bean.common.entity.User;
import org.example.clouddemo.user.service.common.param.LoginParam;
import org.example.clouddemo.user.service.common.param.RegisterParam;
import org.example.clouddemo.user.service.common.vo.LoginResultVo;
import org.example.clouddemo.user.service.common.vo.UserAppVo;
import org.example.clouddemo.user.service.common.UserService;
import org.example.clouddemo.user.service.common.mapper.UserMapper;
import org.example.common.auth.JWTToken;
import org.example.common.auth.JWTUtils;
import org.example.common.auth.TokenService;
import org.example.common.bean.LoginUser;
import org.example.common.constants.RedisKey;
import org.example.common.exception.AppRunTimeException;
import org.example.common.utils.RedisUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


/**
 * 用户表 服务实现类
 */
@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;

    private final PasswordEncoder passwordEncoder;

    private final TokenService tokenService;

    /**
     * 带条件的用户表数据分页查询接口
     * @param page 页面对象
     * @param user 用户对象
     * @return 执行结果
     */
    @Override
    public IPage<User> selectPageVo(Page<User> page, User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user); // where 条件
        queryWrapper.orderByDesc("create_time"); // 按照用户的创建时间进行排序
        return baseMapper.selectPage(page, queryWrapper);
    }


    @Override
    public User selectOne(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public int create(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int update(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public int delete(String id) {
        return userMapper.deleteById(id);
    }

    /**
     * 用户注册功能
     * @param param 注册参数
     * @return 用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long register(RegisterParam param) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername, param.getUsername());
        User user = userMapper.selectOne(queryWrapper);

        // 判断用户是否存在
        if (user != null) {
            throw new AppRunTimeException("已存在用户");
        }

        // 新建用户
        User addUser = new User();
        addUser.setId(IdUtil.getSnowflake().nextId());
        addUser.setUsername(param.getUsername());
        // 临时调试：密码明文存储（生产环境禁用）
        addUser.setPassword(param.getPassword()); // 明文密码
        // addUser.setPassword(passwordEncoder.encode(param.getPassword())); // 原加密代码
        
        // 设置其他可能需要的字段
        addUser.setNickname(param.getUsername()); // 昵称默认为用户名
        addUser.setEnableFlag(true); // 默认启用
        addUser.setMoney(0.0); // 设置默认余额为0
        addUser.setCreateTime(LocalDateTime.now()); // 设置创建时间
        addUser.setUpdateTime(LocalDateTime.now()); // 设置更新时间

        //新建用户
        userMapper.insert(addUser);
        return addUser.getId();
    }

    /**
     * 用户登录功能
     * @param param 用户登录参数
     * @return 登录信息
     */
    @Override
    public LoginResultVo login(LoginParam param) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername, param.getUsername());
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new AppRunTimeException("用户不存在!");
        }

        // 临时调试：明文密码比较（生产环境禁用）
        boolean isMatch = param.getPassword().equals(user.getPassword()); // 明文比较
        // boolean isMatch = passwordEncoder.matches(param.getPassword(), user.getPassword()); // 原加密验证

        if (!isMatch) {
            throw new AppRunTimeException("密码错误!");
        }

        LoginResultVo loginResultVo = new LoginResultVo();

        // 创建登录用户
        LoginUser loginUser = new LoginUser();
        loginUser.setId(user.getId());
        loginUser.setUserName(user.getUsername());
        loginUser.setUserType(LoginUser.USER_TYPE_APP);
        loginUser.setLoginType(LoginUser.LOGIN_TYPE_PWD);

        String uuid = tokenService.createToken(loginUser); //  生成校验token

        String loginUserJson = JSON.toJSONString(loginUser);

        //可以把 用户登录信息加载 放在jwt token中
        JWTToken jwtToken = JWTUtils.getJWT(loginUserJson, uuid, "user", "app");
        loginResultVo.setToken(jwtToken.getAccess_token());

        //把用户信息 放在 redis上
        String key = RedisKey.TOKEN("app", uuid);
        //保存7天
        RedisUtil.set(key, loginUserJson, 7 * RedisUtil.TIME_DAYS_S);

        return loginResultVo;
    }

    /**
     * 用户信息显示功能
     * @param userId 用户id
     * @return 用户信息
     */
    @Override
    public UserAppVo getInfo(Long userId) {
        System.out.println("getInfo服务方法开始执行，用户ID: " + userId);
        
        User user = userMapper.selectById(userId);
        System.out.println("从数据库查询到的用户: " + user);
        
        if (user == null) {
            System.err.println("用户不存在，ID: " + userId);
            throw new AppRunTimeException("找不到数据!");
        }
        
        UserAppVo userAppVo = BeanUtil.copyProperties(user, UserAppVo.class);
        System.out.println("转换后的UserAppVo: " + userAppVo);
        System.out.println("UserAppVo的JSON: " + JSON.toJSONString(userAppVo));
        
        return userAppVo;
    }
}
